<template>
  <!-- 人员弹窗 -->
  <a-modal
    centered
    :title="headerTitle"
    :visible.sync="dialogVisible"
    ok-text=""
    width="1200px"
    @cancel="handleCancel"
    @ok="handleConfirm"
  >
    <a-row :gutter="10">
      <!-- <a-col v-if="address" :span="24" class="mb20">
        {{ address }}
      </a-col> -->
      <!-- 侧边栏 -->
      <a-col v-if="needTree" :span="6" style="border-right: 1px solid #d9d9d9">
        <!-- 公司组织树搜索 -->
        <tree-organization
          v-if="dialogVisible"
          ref="treeOrganization"
          :auto-select="false"
          :project-dept-org-id="projectDeptOrgId"
          :selected-keys.sync="selectedKeys"
          :select-options.sync="selectOptions"
          @loader="search"
        />
      </a-col>
      <!-- 主内容 -->
      <a-col :span="needTree ? 18 : 24">
        <a-input-search
          v-model="nameLike"
          placeholder="请输入员工名称"
          class="mb12"
          :max-length="30"
          @search="search"
        />
        <div style="maxheight: 150px; overflow: auto">
          <a-tag
            v-for="(person, index) in persons"
            :key="person.id"
            class="mb20"
            closable
            color="#108ee9"
            @close="() => handleClose(person, index)"
          >
            {{ person.name }}
          </a-tag>
        </div>

        <a-button
          v-if="isMutilple"
          class="mb12"
          :disabled="rowSelection.selectedRowKeys.length < 1"
          type="primary"
          icon="plus"
          @click="handleAddMore"
        >
          批量添加
        </a-button>
        <!-- 表格 -->
        <s-table
          v-if="dialogVisible"
          ref="table"
          :scroll="{ y: 400 }"
          table-layout="fixed"
          size="default"
          :row-key="(row) => row.id || row.employeeId"
          :columns="columns"
          :row-selection="isMutilple ? rowSelection : null"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          show-pagination="auto"
          @onSelect="handleSubmit"
        >
          <span slot="postPNames" slot-scope="text">
            <div class="ellipsis" :title="filterPostPName(text)">{{ filterPostPName(text) }}</div>
          </span>
          <!-- 表格操作栏 -->
          <span slot="actions" slot-scope="text, record">
            <a v-if="isMutilple" :disabled="record.isAdd" @click="handleSubmit(record)">{{
              record.isAdd ? '已添加' : '添加'
            }}</a>
            <a v-else @click="selectPerson(record)">{{ record.isAdd ? '删除' : '添加' }}</a>
          </span>
        </s-table>
      </a-col>
    </a-row>
    <!-- 页脚操作栏 -->
    <div v-if="isMutilple" slot="footer" class="btn_box">
      <a-button type="primary" @click="handleCancel"> 关闭 </a-button>
      <a-button v-if="isConfirm" type="primary" @click="confirmSingle"> 确定 </a-button>
    </div>
    <div v-else slot="footer" class="btn_box">
      <a-button type="default" @click="handleCancel"> 取消 </a-button>
      <a-button type="primary" @click="confirmSingle"> 确定 </a-button>
    </div>
  </a-modal>
</template>

<script>
import { STable } from '@/components' // 表格
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import { getOrgsTree } from '@/api/subassembly/TreeSelectOrganization'
import { getOneOrgUsers } from '@/api/commons'

const mutilpleColumn = [
  {
    title: '员工名称',
    dataIndex: 'name',
    width: '25%'
  },
  {
    title: '当前所在岗位',
    ellipsis: true,
    dataIndex: 'postPNames',
    customRender(text, record, index) {
      return record.postPNames || '-'
    }
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '100px',
    scopedSlots: { customRender: 'actions' }
  }
]
const mutilpleColumnMore = [
  {
    title: '员工名称',
    dataIndex: 'name',
    width: '25%'
  },
  {
    title: '员工编号',
    dataIndex: 'jobNum'
  },
  {
    title: '电话号码',
    dataIndex: 'phoneNum'
  },
  {
    title: '当前所在岗位',
    ellipsis: true,
    dataIndex: 'postPNames',
    customRender(text, record, index) {
      return record.postPNames || '-'
    }
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '100px',
    scopedSlots: { customRender: 'actions' }
  }
]

const singleColumn = [
  {
    title: '员工名称',
    dataIndex: 'name'
  },
  {
    title: '电话号码',
    dataIndex: 'phoneNum'
  },
  {
    title: '当前所在岗位',
    ellipsis: true,
    dataIndex: 'postPNames',
    customRender(text, record, index) {
      return record.postPNames || '-'
    }
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '100px',
    scopedSlots: { customRender: 'actions' }
  }
]
export default {
  name: 'SelectPersonModal',
  components: {
    STable,
    TreeOrganization
  },
  props: {
    // 显隐控件
    visible: {
      type: Boolean,
      default() {
        return false
      }
    },
    projectDeptOrgId: {
      type: String,
      default() {
        return ''
      }
    },
    address: {
      type: String,
      default() {
        return ''
      }
    },
    // 表单
    form: {
      type: [Object],
      default() {
        return {}
      }
    },
    // 标题
    headerTitle: {
      type: String,
      default() {
        return '选择人员'
      }
    },
    // 列表api
    api: {
      type: Object,
      default() {
        return {}
      }
    },
    // 列表api请求axios
    loadList: {
      type: String,
      default() {
        return 'getList'
      }
    },
    //回显的person
    personsList: {
      type: Array,
      default() {
        return []
      }
    },
    // 是否显示组织树
    needTree: {
      type: Boolean,
      default: () => true
    },
    // 是否多选
    isMutilple: {
      type: Boolean,
      default: false
    },
    // 多选情况是否需要确定按钮,在非表单使用打开弹窗需要确定按钮
    isConfirm: {
      type: Boolean,
      default: false
    },
    // 多选情况下是否需要员工编号和电话号码
    isMore: {
      type: Boolean,
      default: true
    },
    // 初始化之前
    beforeInit: [Function, Promise]
  },
  data() {
    return {
      persons: [],
      queryParam: {},
      nameLike: '',
      selectedKeys: {},
      // 表格复选框配置
      rowSelection: {
        selectedRowKeys: [],
        onChange(selectedRowKeys, selectedRows) {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        },

        getCheckboxProps: (record) => ({
          props: {
            disabled: record.isAdd
          }
        })
      },
      loadData: async (parameter) => {
        // if (this.args.orgId) {
        if (this.beforeInit) {
          const res = await this.beforeInit()
          if (!res) {
            return
          }
        }
        const requestParameters = Object.assign({}, parameter, this.args)
        requestParameters.pageNumber = requestParameters.pageNo
        this.rowSelection.selectedRows = []
        return getOneOrgUsers(requestParameters).then((res) => {
          let obj = {}
          obj.currentPage = requestParameters.pageNo
          obj.pageSize = requestParameters.pageSize
          obj.totalPage = Math.ceil(res.data.total / requestParameters.pageSize)
          obj.totalSize = res.data.total
          obj.data = res.data.list
          obj.data.forEach((item) => {
            item.isAdd = false
            this.persons?.forEach((i) => {
              if (item.userId == i.userId) {
                item.isAdd = true
                Object.assign(i, item)
              }
            })
          })
          !this.init && (this.init = true)
          return obj
        })
        // }
      },
      selectOptions: {},
      init: false // 初始化标识
    }
  },
  computed: {
    // 树节点api
    apiTree() {
      return { getOrgsTree }
    },
    // 与父组件绑定visible
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (e) {
        this.$emit('update:visible', e)
      }
    },
    // 表格列表请求参数
    args() {
      let args = {}
      // 添加树节点id
      if (this.selectedKeys.length > 0) {
        args.rootOrgId = this.selectedKeys[0]
      }
      // 若表单不为空
      if (Object.keys(this.form)?.length) {
        Object.assign(args, this.form)
      }
      // 若关键词存在
      this.nameLike && (args.nameLike = this.nameLike)
      return args
    },
    columns() {
      if (this.isMutilple) {
        if (this.isMore) {
          return mutilpleColumnMore
        } else {
          return mutilpleColumn
        }
      }
      return singleColumn
    }
  },
  watch: {
    visible(e) {
      if (e) {
        this.persons = this.personsList
        this.needTree &&
          !this.$refs.treeOrganization &&
          this.$nextTick(() => {
            this.$refs.treeOrganization.getList()
          })
        this.$nextTick(async () => {
          this.rowSelection.selectedRows = []
          this.init === true && this.search()
        })
      } else {
        // 重置关键词
        this.nameLike = ''
      }
    }
  },
  methods: {
    /**
     * 单选时的确认操作
     */
    confirmSingle() {
      if (!this.persons.length) {
        this.$message.warning('请添加人员')
        return
      }
      this.$emit('confirmSelect', this.persons[0])
      this.$emit('confirmSelects', this.persons)
    },
    handleClose(removedPerson, index) {
      this.persons.splice(index, 1)
      this.$refs.table.loadData()
    },
    delPerson(id) {
      const idx = this.persons.findIndex(item=>item.id === id)
      this.persons.splice(idx, 1)
    },
    handleConfirm() {
      this.handleCancel()
      this.$emit('confirm', this.persons)
    },
    filterPostPName(val) {
      if (val === null) return ''
      return (
        val.reduce &&
        val.reduce((pre, cur) => {
          return pre === '' ? cur : pre + '、' + cur
        }, '')
      )
    },
    handleAddMore() {
      let list = []
      this.rowSelection.selectedRows.forEach((item) => {
        if (!item.isAdd) {
          item.isAdd = true
          list.push(item)
        }
      })
      this.$refs.table.loadData()
      list.forEach((item) => {
        this.persons.push(item)
      })

      // this.$emit('confirms', list)
      // 追加一个额外方法 不知道页面使用的地方多不多 单独取个名字 以防止冲突
      this.$emit('confirmSelect', this.persons)
    },
    // 头部搜索
    search() {
      // console.log('aaa')
      this.$refs.table.refresh(true)
    },
    /**
     * 单选模式下，进行添加删除操作
     */
    selectPerson(record) {
      // 已添加的数据需要删除
      if (record.isAdd) {
        record.isAdd = false
        const index = this.persons.findIndex((item) => item.id === record.id)
        this.persons.splice(index, 1)
        this.$refs.table.loadData()
        return
      }
      if (this.persons.length > 0) {
        this.$message.warning('请先删除已添加人员再进行添加')
        return
      }
      record.isAdd = true
      this.$refs.table.loadData()
      this.persons.push(record)
    },
    handleSubmit(record) {
      console.log('aa')
      record.isAdd = true
      this.$refs.table.loadData()
      this.persons.push(record)
      // that.$emit('confirm', record)
    },
    handleCancel() {
      this.dialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}
</style>
